package com.cscj.android.repository.settings.impl

import android.os.Build
import androidx.room.withTransaction
import com.cscj.android.repository.db.CacheDatabase
import com.cscj.android.repository.db.dao.UserAgentDao
import com.cscj.android.repository.db.entity.UserAgentEntity
import com.cscj.android.repository.settings.Settings
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.firstOrNull
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import java.util.Locale

class UserAgentSettingImpl : Settings.UserAgentSetting, KoinComponent {

    companion object {
        private val UA_Android = "Mozilla/5.0 (Linux; Android " + Build.VERSION.RELEASE + ";"+ Locale.SIMPLIFIED_CHINESE  + ";" + Build.MODEL +") AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5"
        private val UA_Desktop = "Mozilla/5.0 (X11; Linux " + System.getProperty("os.arch") + ")"
        private const val UA_IOS =
            "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5"
    }

    private val initialData by lazy {
        listOf(
            UserAgentEntity(id = 1, name = "Android", content = UA_Android, preferred = true),
            UserAgentEntity(id = 2, name = "iPhone", content = UA_IOS, preferred = false),
            UserAgentEntity(id = 3, name = "电脑模式", content = UA_Desktop, preferred = false),
        )
    }

    private val userAgentDao: UserAgentDao by inject()
    private val database: CacheDatabase by inject()


    override suspend fun init() {
        database.withTransaction {
            val currentAgent = userAgentDao.currentUserAgent().firstOrNull()
            userAgentDao.batchInsert(initialData)
            currentAgent?.also { agent ->
                switchUserAgent(agent.id)
            }
        }
    }

    override fun currentUserAgent(): Flow<UserAgentEntity?> {
        return userAgentDao.currentUserAgent()
    }

    override suspend fun switchUserAgent(id: Int) {
        database.withTransaction {
            userAgentDao.updatePreferred(false)
            userAgentDao.updatePreferredById(id, true)
        }
    }

    override suspend fun newUserAgent(name: String, content: String, preferred: Boolean) {
        userAgentDao.upsertUserAgent(
            UserAgentEntity(
                name = name, content = content, preferred = preferred
            )
        )
    }

    override fun userAgentList(): Flow<List<UserAgentEntity>> {
        return userAgentDao.userAgentList()
    }
}